//
//  UWHistoryCell.m
//  Urban Words
//
//  Created by sebastian on 2011-12-02.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UWHistoryCell.h"
#import <QuartzCore/CALayer.h>
#import "UWApi.h"

#define ROW_HEIGHT 38
#define CELL_HEIGHT 38
#define WORDS_LEFT_PADDING 8
#define WORDS_TOP_PADDING 10
#define WORDS_BOTTOM_PADDING 5
#define WORDBUBBLE_PADDING 10
#define WORDBUBBLE_HEIGHT 20
#define FONTSIZE 14
#define POINTS_LEFT_PADDING 4

@interface UWHistoryCell()
- (NSString *)getDefinitionOfWord:(NSString *)word;
@end

@implementation UWHistoryCell

@synthesize arrow, open;

- (id)initWithLeftOrRight:(BOOL)leftOrRight section:(NSInteger)sectionNumber delegate:(id<SectionHeaderViewDelegate>)delegate {
    if (self) {
        [super init];
        // Initialization code
        [self setMultipleTouchEnabled:NO];
        // Custom initialization
        self.backgroundColor = [UIColor whiteColor];
        leftSide = leftOrRight;
        if (leftSide) {
            bubbleColor = [UIColor colorWithRed:1 green:0.6 blue:0 alpha:1];
        } else {
            bubbleColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
        }
        //self.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:0.2];
        parentTable = delegate;
        section = sectionNumber;
        wordLabels = [[NSMutableArray alloc] init];
        explanation.hidden = YES;
        open = NO;
        //[self makeExplanation:nil];
    }
    return self;
}

- (void)chooseExplanation {
    if (open) {
        open = NO;
        selectedWord.alpha = 1;
        if ([parentTable respondsToSelector:@selector(sectionHeaderView:sectionClosed:)]) {
            [parentTable sectionHeaderView:self sectionClosed:section];
        }
    } else {
        open = YES;
        selectedWord.alpha = 0.5;
        [self makeExplanation:selectedWord];
    }
}

- (void)makeExplanation:(UILabel *)wordLabel {
    NSLog(@"Make Exp.");
    [explanation release];
    explanation = [[UILabel alloc] init];
    explanation.font = [UIFont systemFontOfSize:FONTSIZE];
    explanation.lineBreakMode = UILineBreakModeWordWrap;
    explanation.textAlignment = UITextAlignmentCenter;
    explanation.numberOfLines = 50;
    explanation.textColor = [UIColor colorWithRed:0.15 green:0.15 blue:0.15 alpha:1];
    explanation.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:0.92 green:0.92 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    explanation.text = [self getDefinitionOfWord:wordLabel.text];
    
    // Get size of text in points.
    CGSize size = [explanation.text sizeWithFont:[UIFont systemFontOfSize:FONTSIZE] constrainedToSize:CGSizeMake(300, 4000) lineBreakMode:UILineBreakModeWordWrap];
    
    explanation.frame = CGRectMake(10, 0, 300, size.height+WORDBUBBLE_PADDING*2);
    if ([parentTable respondsToSelector:@selector(sectionHeaderView:sectionOpened:)]) {
        NSLog(@"%@",explanation.text);
        [parentTable sectionHeaderView:self sectionOpened:section];
    }
}

- (CGFloat)getRowHeight {
    return countY+WORDBUBBLE_HEIGHT+WORDS_BOTTOM_PADDING;
}

- (UILabel *)getExplanation {
    return explanation;
}

- (void)createLabels:(NSArray *)words {
    [wordLabels release];
    wordLabels = [[NSMutableArray alloc] init];
    countX = leftSide?0:320;
    countY = WORDS_TOP_PADDING;
    for (int i=0; i<words.count; i=i+1) {
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(countX+WORDS_LEFT_PADDING, countY, 320, WORDBUBBLE_HEIGHT)];
        textLabel.font = [UIFont systemFontOfSize:FONTSIZE];
        textLabel.text = [[words objectAtIndex:i] capitalizedString];
        textLabel.textAlignment = UITextAlignmentCenter;
        textLabel.textColor = [UIColor blackColor];
        textLabel.layer.cornerRadius = 5.0;
        textLabel.layer.masksToBounds = YES;
        textLabel.backgroundColor = bubbleColor;
        if (leftSide) {
            CGSize size = [textLabel.text sizeWithFont:[UIFont systemFontOfSize:FONTSIZE] ];
            if ((countX+WORDS_LEFT_PADDING+size.width+WORDBUBBLE_PADDING)>260) {
                countY = countY+WORDBUBBLE_HEIGHT+WORDS_TOP_PADDING;
                textLabel.frame = CGRectMake(WORDS_LEFT_PADDING, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
                countX = WORDS_LEFT_PADDING+size.width+WORDBUBBLE_PADDING;
            } else {
                textLabel.frame = CGRectMake(countX+WORDS_LEFT_PADDING, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
                countX = countX + WORDS_LEFT_PADDING + size.width + WORDBUBBLE_PADDING;
            }
        } else {
            CGSize size = [textLabel.text sizeWithFont:[UIFont systemFontOfSize:FONTSIZE] ];
            if ((countX-WORDS_LEFT_PADDING-size.width-WORDBUBBLE_PADDING)<80) {
                countY = countY+WORDBUBBLE_HEIGHT+WORDS_TOP_PADDING;
                countX = 320 - WORDS_LEFT_PADDING - size.width - WORDBUBBLE_PADDING;
                textLabel.frame = CGRectMake(countX, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
            } else {
                countX = countX - WORDS_LEFT_PADDING - size.width - WORDBUBBLE_PADDING;
                textLabel.frame = CGRectMake(countX, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
            }
        }
        textLabel.userInteractionEnabled = YES;
        [self addSubview:textLabel];
        [wordLabels addObject:textLabel]; 
        [textLabel release];
    }
    // Add score
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(countX+WORDS_LEFT_PADDING, countY, 320, WORDBUBBLE_HEIGHT)];
    textLabel.font = [UIFont systemFontOfSize:FONTSIZE];
    textLabel.text = [NSString stringWithFormat:@"%@p",score];
    textLabel.textAlignment = UITextAlignmentCenter;
    textLabel.textColor = [UIColor blackColor];
    textLabel.backgroundColor = [UIColor whiteColor];
    if (leftSide) {
        CGSize size = [textLabel.text sizeWithFont:[UIFont systemFontOfSize:FONTSIZE] ];
        if ((countX+POINTS_LEFT_PADDING+size.width+WORDBUBBLE_PADDING)>260) {
            countY = countY+WORDBUBBLE_HEIGHT+WORDS_TOP_PADDING;
            textLabel.frame = CGRectMake(POINTS_LEFT_PADDING, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
            countX = POINTS_LEFT_PADDING+size.width+WORDBUBBLE_PADDING;
        } else {
            textLabel.frame = CGRectMake(countX+POINTS_LEFT_PADDING, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
            countX = countX + POINTS_LEFT_PADDING + size.width + WORDBUBBLE_PADDING;
        }
    } else {
        CGSize size = [textLabel.text sizeWithFont:[UIFont systemFontOfSize:FONTSIZE] ];
        if ((countX-POINTS_LEFT_PADDING-size.width-WORDBUBBLE_PADDING)<80) {
            countY = countY+WORDBUBBLE_HEIGHT+WORDS_TOP_PADDING;
            countX = 320 - POINTS_LEFT_PADDING - size.width - WORDBUBBLE_PADDING;
            textLabel.frame = CGRectMake(countX, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
        } else {
            countX = countX - POINTS_LEFT_PADDING - size.width - WORDBUBBLE_PADDING;
            textLabel.frame = CGRectMake(countX, countY, size.width+WORDBUBBLE_PADDING, WORDBUBBLE_HEIGHT);
        }
    }
    textLabel.userInteractionEnabled = YES;
    [self addSubview:textLabel];
    [wordLabels addObject:textLabel]; 
    [textLabel release];
}

- (void)setWords:(NSArray *)wordlist score:(NSString *)scoreForWords {
    score = scoreForWords;
    // Create labels
    [self createLabels:wordlist];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    NSLog(@"touchesBegan");
    CGPoint test = [[[event allTouches] anyObject] locationInView:self];
    //NSLog(@"touches=%@, event=%f,%f",touches,test.x,test.y);
    touchCancelled = NO;
    //[super touchesBegan:touches withEvent:event];
    for (int i = 0; i<wordLabels.count; i=i+1) {
        selectedWord = [wordLabels objectAtIndex:i];
        if (CGRectContainsPoint(selectedWord.frame , test)) {
            NSLog(@"%@",selectedWord.text);
            selectedWord.alpha = 0.5;
            break;
        } else {
            selectedWord = nil;
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchCancelled = YES;
    if (selectedWord != nil) {
        //selectedWord.alpha = 1;
        if (open) {
            open = NO;
            selectedWord.alpha = 1;
            if ([parentTable respondsToSelector:@selector(sectionHeaderView:sectionClosed:)]) {
                [parentTable sectionHeaderView:self sectionClosed:section];
            }
        } else {
            open = YES;
            selectedWord.alpha = 0.5;
            [self makeExplanation:selectedWord];
        }        
        NSLog(@"touchesEnded.");
    }
    //[super touchesEnded:touches withEvent:event];
    
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchCancelled = YES;
    if (selectedWord != nil) {
        //selectedWord.alpha = 1;
        selectedWord = nil;
        NSLog(@"touchesCancelled.");
    }
    //[super touchesCancelled:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{        
    NSLog(@"touchesMoved.");
    touchCancelled = YES;
   // [super touchesMoved:touches withEvent:event];
}

- (NSString *)getDefinitionOfWord:(NSString *)word 
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.urbandictionary.com/iphone/search/define?term=%@", word]];    
    id tmpDict = [UWApi parseJson:[NSData dataWithContentsOfURL:url]];
    for (NSObject *o in [tmpDict objectForKey:@"list"]) {
        if ([o valueForKey:@"definition"]!=nil) {
            NSLog(@"%@", [o valueForKey:@"definition"]);
            return [o valueForKey:@"definition"];
        }
    }
    
    return @"No definition found.";
}

@end
